// pages/cart/cart.js
import { getElementRect } from '../../utils/common'
import { getMyShoppingCartApi, getCartProductsApi, delCartApi } from '../../api/cart'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    navBarHeight: 0,
    navBarIsFixed: false,
    tabBarHeight: 0,
    cartList: [],
    cartResult: [],
    selectAll: false,
    countPrice: 0
  },

  /**
   * 跳转商品详情
   */
  jumpGoodsInfo(e) {
    const info = e.currentTarget.dataset.info
    const { productId, id } = info
    wx.navigateTo({
      url: `/pages/goodinfo/goodinfo?goodId=${productId}&cartId=${id}`
    })
  },

  /**
   * 计算价格
   */
  computedPrice() {
    let price = 0
    for (let i = 0; i < this.data.cartResult.length; i++) {
      const resultId = this.data.cartResult[i]
      for (let j = 0; j < this.data.cartList.length; j++) {
        const cartId = this.data.cartList[j].id
        const curPrice = Number(this.data.cartList[j].totalAmount) * 100
        if (Number(resultId) === Number(cartId)) {
          price += curPrice
        }
      }
    }
    this.setData({
      countPrice: price / 100
    })
  },

  /**
   * 购物车全选
   */
  selectAllChange(e) {
    let cartResult = []
    if (e.detail) {
      cartResult = this.data.cartList.map((item) => item.id.toString())
    }
    this.setData(
      {
        selectAll: e.detail,
        cartResult
      },
      () => {
        this.computedPrice()
      }
    )
  },

  /**
   * 购物车多选change事件
   */
  onCartChange(e) {
    let selectAll = false
    if (e.detail.length === this.data.cartList.length) {
      selectAll = true
    } else {
      selectAll = false
    }

    this.setData(
      {
        cartResult: e.detail,
        selectAll
      },
      () => {
        this.computedPrice()
      }
    )
  },

  /**
   * 获取购物车列表
   */
  async getMyShoppingCart() {
    const [err, data] = await getMyShoppingCartApi()
    if (err) return
    this.setData({
      cartList: data ?? []
    })
  },

  /**
   * 获取顶部navbar的高度
   */
  async getNavBarHeight() {
    const navBarRect = await getElementRect('#nav-bar', true, this)
    this.setData({
      navBarHeight: navBarRect.height,
      navBarIsFixed: true
    })
  },

  /**
   * 获取底部tabbar的高度
   */
  getTabBarHeight() {
    const tabBarHeight = wx.getStorageSync('tabBarHeight')
    this.setData({
      tabBarHeight
    })
  },

  /**
   * 点击去结算
   */
  async submitHandle() {
    if (this.data.cartResult.length === 0) {
      wx.showToast({
        title: '请先选择要结算的产品',
        icon: 'none'
      })
      return false
    }
    const [err, goodsList] = await getCartProductsApi({ ids: this.data.cartResult.join(',') })
    if (err) return
    // console.log(goodsList)
    const confirmList = []
    for (let i = 0; i < goodsList.length; i++) {
      const { id: cartId, productId: goodId, totalPrice, sampleName, sampleList } = goodsList[i]
      const list = sampleList.map((sample) => {
        const aa = sample.normList.reduce((pre, cur) => {
          return [...pre, ...cur.methodList.filter((method) => method.select === true)]
        }, [])
        console.log(aa)
        return {
          sampleNumber: sample.sampleNum,
          methodResult: aa.map((item) => item.id.toString()),
          countPrice: aa.reduce((pre, cur) => pre + Number(cur.price) * 100, 0) / 100
        }
      })
      confirmList.push({
        cartId,
        goodId,
        sampleName,
        sampleList: list,
        totalPrice
      })
    }
    wx.setStorageSync('confirmPrevData', confirmList)

    const entrustPopup = this.selectComponent('#entrust-popup')
    entrustPopup.showPopup()
  },

  /**
   * 跳转确认订单页面
   */
  jumpConfirm() {
    wx.navigateTo({
      url: `/pages/confirmOrder/confirmOrder`
    })
  },

  /**
   * 删除购物车
   */
  delCard() {
    if (this.data.cartResult.length === 0) {
      wx.showToast({
        title: '请先选择要删除的产品',
        icon: 'none'
      })
      return false
    }

    wx.showModal({
      title: '提示',
      content: `您确定要删除该${this.data.cartResult.length}条 已经加入购物车的样品`,
      complete: async (res) => {
        if (res.confirm) {
          const [err] = await delCartApi({ ids: this.data.cartResult.join(',') })
          if (err) return
          wx.showToast({
            title: '删除成功',
            icon: 'none'
          })

          this.getMyShoppingCart()
        }
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // this.getNavBarHeight()
    // this.getTabBarHeight()
    this.getNavBarHeight()
    setTimeout(() => {
      this.getTabBarHeight()
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init()
    this.getMyShoppingCart()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {}
})
